<?php

namespace app\index\traits;

use app\common\model\Area;
use app\common\model\Member;
use app\common\traits\LocationTrait;
use app\index\service\LocationCityService;
use think\facade\Request;

/**
 * 登录后定位
 * Trait SessionAfterLocationTrait
 * @package app\index\traits
 */
trait SessionAfterLocationTrait
{
    use LocationTrait;

    /**
     * 设置当前用户城市
     * @param Member $member
     * @return void
     */
    private function setLocation(Member $member): void
    {
        $ip = Request::ip();
        $phone = $member->phone;

        if (not_blank($ip)) {
            $data = $this->getProvinceCityByIp($ip);

            $provinceName = $data['provinceName'] ?? '';
            $cityName = $data['cityName'] ?? '';

            // 查询城市并赋值
            if (is_blank($cityName)) {
                $cityName = $provinceName;
            }

            $city = Area::where('name', $cityName)
                ->where('province', '<>', '0')
                ->where('city', '0')
                ->where('status', 0)
                ->find();

            if ($city) {
                // 更新当前定位
                $this->getLocationCityService()->updateLocationCity($member, $city);
                return;
            }
        }

        if (not_blank($phone)){

            $data = $this->getProvinceCityByPhone($phone);

            $provinceName = $data['provinceName'] ?? '';
            $cityName = $data['cityName'] ?? '';

            // 查询城市并赋值
            if (is_blank($cityName)) {
                $cityName = $provinceName;
            }

            $city = Area::where('name', $cityName)
                ->where('province', '<>', '0')
                ->where('city', '0')
                ->where('status', 0)
                ->find();

            if ($city) {
                // 更新当前定位
                $this->getLocationCityService()->updateLocationCity($member, $city);
                return;
            }

        }


    }

    private function getLocationCityService(): LocationCityService
    {
        return app(LocationCityService::class);
    }
}